package com.atguigu.day09;

import com.atguigu.utils.Event;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

// 超时订单的检测
public class Example3 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<Event> stream = env
                .fromElements(
                        new Event("order-1", "create-order", 1000L),
                        new Event("order-2", "create-order", 2000L),
                        new Event("order-1", "pay-order", 3000L)
                )
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Event>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                                    @Override
                                    public long extractTimestamp(Event element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })
                );

        // 定义模板
        Pattern<Event, Event> pattern = Pattern
                .<Event>begin("create")
                .where(new SimpleCondition<Event>() {
                    @Override
                    public boolean filter(Event event) throws Exception {
                        return event.value.equals("create-order");
                    }
                })
                .next("pay")
                .where(new SimpleCondition<Event>() {
                    @Override
                    public boolean filter(Event event) throws Exception {
                        return event.value.equals("pay-order");
                    }
                })
                // 要求两个事件在5秒钟之内发生
                .within(Time.seconds(5));

        SingleOutputStreamOperator<String> result = CEP
                .pattern(stream.keyBy(r -> r.key), pattern)
                .flatSelect(
                        // 侧输出标签，用来接收超时信息
                        new OutputTag<String>("timeout-info") {
                        },
                        // 匿名类，用来向侧输出流发送超时信息
                        new PatternFlatTimeoutFunction<Event, String>() {
                            @Override
                            public void timeout(Map<String, List<Event>> map, long timestamp, Collector<String> out) throws Exception {
                                // map {
                                //   "create": [Event]
                                // }
                                Event create = map.get("create").get(0);
                                out.collect(create.key + "超时未支付");
                            }
                        },
                        // 匿名类，向下游发送正常支付的信息
                        new PatternFlatSelectFunction<Event, String>() {
                            @Override
                            public void flatSelect(Map<String, List<Event>> map, Collector<String> out) throws Exception {
                                // map {
                                //   "create": [Event],
                                //   "pay": [Event]
                                // }
                                Event create = map.get("create").get(0);
                                Event pay = map.get("pay").get(0);
                                out.collect(create.key + "已支付，支付时间：" + pay.ts);
                            }
                        }
                );

        result.print("主流");
        result.getSideOutput(new OutputTag<String>("timeout-info"){}).print("侧输出流");

        env.execute();
    }
}
